import {defineComponent} from "vue";
import {BaseCommonMixin} from "./BaseCommonMixin";
import {EventFirstParam} from "../types";
import {StringUtils} from "../../../utils/StringUtils";
import typeOfUtils from "../../../utils/type-of-utils";

export const ComsCommonMixin = defineComponent({
  mixins: [BaseCommonMixin],
  computed: {
    options() {
      return this.item.props?.options || []
    },
    plusEventsFirstParam(): EventFirstParam {
      return {
        formData: this.formData,
        item: this.item
      }
    },
    disabled() {
      if (this.formVm.$attrs.disabled === true) {
        return true
      }
      // 扩展disabled
      let disabled = this.item.props?.disabled
      if (typeOfUtils.isFunction(disabled)) {
        return disabled(this.plusEventsFirstParam)
      }
      return disabled || false
    },
    style() {
      let result = {
        ...this.item.props?.style
      }
      if (this.formVm.search) {
        return {
          width: this.formVm.inputSearchWidth,
          ...result,
        }
      }
      return result
    },
    vBind() {
      // 扩展事件
      let events = {}
      if (this.item.events) {
        Object.keys(this.item.events).forEach(key => {
          if (key === this.isSearchEmitSearchEventName) {
            return
          }
          let name = 'on' + StringUtils.firstToUp(key)
          events[name] = (...args) => {
            this.itemEvents(args, key)
          }
        })
      }
      return {
        ...this.item.props,
        disabled: this.disabled,
        ...events,
        style: this.style
      }
    }
  },
  created() {
    if (this.formVm.createdInitValue) {
      if (this.formVm.createdHasInitValueNotInit) {
        let value = this.formData[this.item.prop]
        if (typeOfUtils.isEmpty(value)) {
          this._comInitValue()
        }
      } else {
        this._comInitValue()
      }
    }
  },
  data() {
    return {
      // 配置忽略 isSearchEmitSearch 的名字，不然会有重复调用
      isSearchEmitSearchEventName: ''
    }
  },
  methods: {
    _comInitValue() {
      if (this.item.initValue) {
        this.formData[this.item.prop] = this.item.initValue
      } else {
        if (this.initValue) {
          this.initValue()
        } else {
          this.formData[this.item.prop] = ''
        }
      }
    },
    itemEvents(args, eventName) {
      if (Array.isArray(args)) {
        this.item.events[eventName](this.plusEventsFirstParam, ...args)
      } else {
        this.item.events[eventName](this.plusEventsFirstParam, args)
      }
    },
    /**
     * 绑定事件的时候，
     * 多个参数用 arguments
     * 单个参数用 $event
     */
    isSearchEmitSearch(args, eventName: string) {
      if (this.item && this.item.events && this.item.events[eventName]) {
        this.itemEvents(args, eventName)
      }
      if (this.formVm.search) {
        if (this.item.search) {
          this.formVm.$emit('search')
        }
      }
    },
    resetField() {
      this._comInitValue()
    },
  }
})
